<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="98px"
    >
      <el-form-item label="订单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="业务员编号" prop="jobCode">
        <el-input
          v-model="queryParams.jobCode"
          placeholder="请输入业务员编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <!-- <el-form-item label="机构名称" prop="organizationId">
        <el-input v-model="queryParams.organizationId" placeholder="请选择机构" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->

      <el-form-item label="机构名称" prop="organizationId">
        <el-tree-select
          v-model="queryParams.organizationId"
          :data="organizationOptions"
          :props="{
            value: 'organizationId',
            label: 'orgName',
            children: 'children',
          }"
          value-key="organizationId"
          placeholder="请选择机构"
          clearable
          check-strictly
          @change="handleQuery"
        />
      </el-form-item>

      <!-- <el-form-item label="交易金额" prop="amount">
        <el-input v-model="queryParams.amount" placeholder="请输入交易金额" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->

      <el-form-item label="业务名称" prop="businessName">
        <el-input
          v-model="queryParams.businessName"
          placeholder="请输入业务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <!-- <el-form-item label="订单提交时间" prop="submitTime">
        <el-date-picker clearable v-model="queryParams.submitTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择订单提交时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="订单提交时间" prop="submitTime">
        <el-date-picker
          v-model="queryParams.submitTimeRange"
          type="daterange"
          value-format="YYYY-MM-DD"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="订单状态" prop="orderStatus">
        <el-select
          v-model="queryParams.orderStatus"
          placeholder="请选择订单状态"
          clearable
        >
          <el-option
            v-for="dict in order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in wdm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:businessOrder:add']"
          >新增</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:businessOrder:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:businessOrder:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:businessOrder:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 border 添加边框提升可读性 resizable 启用列宽拖拽 -->
    <!-- :header-cell-style="{ background: '#111111' }" -->
    <!-- style="width: 100%" -->
    <el-table
      v-loading="loading"
      :data="businessOrderList"
      border
      resizable
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- prop="orderId" -->
      <el-table-column label="序号" type="index" width="60" align="center" />
      <!-- <el-table-column label="订单编号" align="center" min-width="240" prop="orderCode" /> -->
      <el-table-column
        label="姓名"
        align="center"
        min-width="240"
        prop="name"
      />
      <!-- <el-table-column label="联系电话" align="center" min-width="150" prop="phone" /> -->
      <el-table-column
        label="所属机构"
        align="center"
        min-width="150"
        prop="orgName"
      />
      <!-- <el-table-column label="业务员编号" align="center" min-width="150" prop="jobCode" /> -->
      <!-- <el-table-column label="关联员工ID" align="center" prop="employeeId" /> -->
      <!-- <el-table-column label="关联机构ID" align="center" prop="organizationId" /> -->
      <el-table-column
        label="交易金额"
        align="center"
        min-width="150"
        prop="amount"
      />
      <el-table-column
        label="业务名称"
        align="center"
        min-width="200"
        prop="businessName"
      />

      <el-table-column
        label="订单状态"
        min-width="100"
        align="center"
        prop="orderStatus"
      >
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>

      <el-table-column
        label="订单提交时间"
        align="center"
        prop="submitTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.submitTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="创建人" align="center" min-width="240" prop="createBy" />
      <el-table-column label="订单提交时间" align="center" prop="submitTime" width="180">
        <template #default="scope">
          <span v-if="scope.row.submitTime">{{ parseTime(scope.row.submitTime, "{y}-{m}-{d}") }}</span>
          <span v-else-if="scope.row.startTime && scope.row.endTime">
            {{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }} 至 {{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}
          </span>
        </template>
      </el-table-column> -->

      <!-- <el-table-column label="修改人" align="center" min-width="240" prop="updateBy" />
      <el-table-column label="更新时间" align="center" min-width="150" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->

      <!-- <el-table-column label="支付类型" align="center" prop="payType">
        <template #default="scope">
          <dict-tag :options="payment_method" :value="scope.row.payType" />
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template #default="scope">
          <dict-tag :options="payment_status" :value="scope.row.payStatus" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <el-table-column
        label="备注信息"
        align="center"
        min-width="150"
        prop="remark"
      />

      <el-table-column
        label="操作"
        min-width="240"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['ruoyi:businessOrder:edit']"
            >查看</el-button
          >

          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:businessOrder:edit']">修改</el-button> -->

          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:businessOrder:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改业务订单信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="businessOrderRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <!-- <el-form-item label="订单编号" prop="orderCode">
          <el-input v-model="form.orderCode" placeholder="请输入订单编号" />
        </el-form-item> -->

        <el-form-item label="员工ID" prop="employeeId">
          <el-input v-model="form.employeeId" placeholder="请输入关联员工ID" />
        </el-form-item>
        <el-form-item label="机构ID" prop="organizationId">
          <el-input
            v-model="form.organizationId"
            placeholder="请输入关联机构ID"
          />
        </el-form-item>
        <el-form-item label="交易金额" prop="amount">
          <!-- <el-input v-model="form.amount" placeholder="请输入交易金额" /> -->
          <el-input
            v-model.number="queryParams.amount"
            type="number"
            :precision="2"
            step="0.01"
          />
        </el-form-item>
        <el-form-item label="业务名称" prop="businessName">
          <el-input v-model="form.businessName" placeholder="请输入业务名称" />
        </el-form-item>
        <el-form-item label="订单提交时间" prop="submitTime">
          <el-date-picker
            clearable
            v-model="form.submitTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择订单提交时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
            <el-option
              v-for="dict in order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in wdm_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-radio-group v-model="form.delFlag">
            <el-radio
              v-for="dict in del_flag"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看订单信息对话框 -->
    <el-dialog :title="title" v-model="viewOpen" width="60%" append-to-body>
      <el-card class="box-card">
        <template #header>
          <div class="clearfix" style="text-align: center">
            <span style="font-size: 20px; color: #1890ff"
              >业务订单基本信息</span
            >

            <el-descriptions
              title="基本信息"
              :model="form"
              label-width="120px"
              border
            >
              <el-descriptions-item label="订单编号">{{
                form.orderCode
              }}</el-descriptions-item>
              <el-descriptions-item label="员工姓名">{{
                form.name
              }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{
                form.phone
              }}</el-descriptions-item>
              <el-descriptions-item label="机构名称">{{
                form.orgName
              }}</el-descriptions-item>
              <el-descriptions-item label="交易金额">{{
                form.amount
              }}</el-descriptions-item>
              <el-descriptions-item label="业务名称">{{
                form.businessName
              }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </template>
      </el-card>

      <el-card class="box-card">
        <template #header>
          <div class="clearfix" style="text-align: center">
            <span style="font-size: 20px; color: #1890ff"
              >业务订单基本信息</span
            >

            <el-descriptions
              title="状态信息"
              :model="form"
              label-width="120px"
              border
            >
              <el-descriptions-item label="订单状态">{{
                dictLabel(order_status, form.orderStatus)
              }}</el-descriptions-item>
              <el-descriptions-item label="支付类型">{{
                dictLabel(payment_method, form.payType)
              }}</el-descriptions-item>
              <el-descriptions-item label="支付状态">{{
                dictLabel(payment_status, form.payStatus)
              }}</el-descriptions-item>
              <el-descriptions-item label="订单提交时间">{{
                parseTime(form.submitTime)
              }}</el-descriptions-item>
              <el-descriptions-item label="创建人">{{
                form.createBy
              }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{
                parseTime(form.createTime)
              }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{
                parseTime(form.updateTime)
              }}</el-descriptions-item>
              <el-descriptions-item label="备注信息" :span="3">{{
                form.remark
              }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </template>
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BusinessOrder">
import { parseTime } from "@/utils/ruoyi";

import { listOrganization } from "@/api/ruoyi/organization";

import {
  listBusinessOrder,
  getBusinessOrder,
  delBusinessOrder,
  addBusinessOrder,
  updateBusinessOrder,
} from "@/api/ruoyi/businessOrder";

const { proxy } = getCurrentInstance();
const { wdm_status, order_status, payment_method, payment_status, del_flag } =
  proxy.useDict(
    "wdm_status",
    "order_status",
    "payment_method",
    "payment_status",
    "del_flag"
  );

const businessOrderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  // 新增查看对话框控制变量
  viewOpen: false,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    employeeId: null,
    organizationId: null,
    amount: null,
    businessName: null,
    // 订单提交时间
    submitTime: null,
    // 订单检索时间段
    submitTimeRange: [],

    orderStatus: null,
    status: null,
    orderCode: null,
    name: null,
    phone: null,
    orgName: null,
    jobCode: null,
    payType: null,
    payStatus: null,
  },
  rules: {
    employeeId: [
      { required: true, message: "关联员工ID不能为空", trigger: "blur" },
    ],
    organizationId: [
      { required: true, message: "关联机构ID不能为空", trigger: "blur" },
    ],
    delFlag: [
      { required: true, message: "删除标志不能为空", trigger: "change" },
    ],
    // orderCode: [
    //   { required: true, message: "订单编号不能为空", trigger: "blur" }
    // ]
  },
});

const { queryParams, form, rules, viewOpen } = toRefs(data);

/** 查询业务订单信息列表 */
function getList() {
  loading.value = true;
  listBusinessOrder(queryParams.value).then((response) => {
    // businessOrderList.value = response.rows;
    // 过滤已删除数据（假设 delFlag 字段标识删除状态）
    businessOrderList.value = response.rows.filter(
      (item) => item.delFlag !== "2"
    );
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    employeeId: null,
    organizationId: null,
    amount: null,
    businessName: null,
    submitTime: null,
    orderStatus: null,
    status: null,
    delFlag: null,
    version: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    orderCode: null,
    name: null,
    phone: null,
    orgName: null,
    jobCode: null,
    payType: null,
    payStatus: null,
  };
  proxy.resetForm("businessOrderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;

  // 将时间范围拆分为两个独立参数
  if (
    queryParams.value.submitTimeRange &&
    queryParams.value.submitTimeRange.length === 2
  ) {
    queryParams.value.startTime = queryParams.value.submitTimeRange[0];
    queryParams.value.endTime = queryParams.value.submitTimeRange[1];
  } else {
    queryParams.value.startTime = null;
    queryParams.value.endTime = null;
  }

  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");

  // 重置时间范围选择
  queryParams.value.submitTimeRange = [];

  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加业务订单信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  // const _orderId = row.orderId || ids.value;
  const _orderId = row?.orderId || (ids.value.length > 0 ? ids.value[0] : null);
  getBusinessOrder(_orderId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改业务订单信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["businessOrderRef"].validate((valid) => {
    if (valid) {
      if (form.value.orderId != null) {
        updateBusinessOrder(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBusinessOrder(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value;
  proxy.$modal
    .confirm('是否确认删除业务订单信息编号为"' + _orderIds + '"的数据项？')
    .then(function () {
      return delBusinessOrder(_orderIds);
    })
    .then(() => {
      // getList();
      handleQuery(); // 使用查询方法替代 getList() 保持参数一致性
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/businessOrder/export",
    {
      ...queryParams.value,
    },
    `businessOrder_${new Date().getTime()}.xlsx`
  );
}

/** 查看按钮操作 */
function handleView(row) {
  const _orderId = row?.orderId || (ids.value.length > 0 ? ids.value[0] : null);
  if (!_orderId) {
    proxy.$modal.msgError("请选择要查看的订单");
    return;
  }

  getBusinessOrder(_orderId).then((response) => {
    form.value = response.data;
    title.value = "订单详情查看";
    viewOpen.value = true;
  });
}

// 辅助函数：根据字典值获取标签
function dictLabel(dict, value) {
  const item = dict.find((d) => d.value === value);
  return item ? item.label : value;
}

// 增强时间格式化显示
function formatTime(time) {
  return time ? parseTime(time, "{y}-{m}-{d} {h}:{i}:{s}") : "N/A";
}

// 添加金额格式化
function formatAmount(amount) {
  return amount ? `¥${parseFloat(amount).toFixed(2)}` : "¥0.00";
}
// 新增部分

const organizationOptions = ref([]);
/** 查询机构信息下拉树结构 */
function getTreeselect() {
  listOrganization().then((response) => {
    organizationOptions.value = [];
    const data = { organizationId: 0, orgName: "顶级节点", children: [] };
    data.children = proxy.handleTree(
      response.data,
      "organizationId",
      "parentId"
    );
    organizationOptions.value.push(data);
  });
}

getList();

// 获取机构信息下拉树结构
getTreeselect();
</script>
